/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package uk.ac.cam.juliet.zedcat.client;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 * @author Chris
 */
public class TwitPic {

    // Takes a File and uploads it to twitpic, returning a url to the
    public static String Upload(File file) {

        try {
            // We need a boundary for configuring the connection.
            String boundary = HTTPPost.createBoundary();

            // Setup a connection to the twitpic API.
            // This one just expects:
            // Twitter username. [username]
            // Twitter password. [password]
            // Binary formatted image data. [media]
            // URL url = new URL("http://twitpic.com/api/upload");
            URL url = new URL("http://www.srcf.ucam.org/juliet/ajax/imagePost.php");
            URLConnection conn = HTTPPost.createConnection(url);
            conn.setRequestProperty("Accept", "*/*");
            conn.setRequestProperty("Content-type", HTTPPost.getContentType(boundary));

            // Some optionals to make things go smoothly
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Cache-Control", "no-cache");

            // Create the Post and add the data.
            HTTPPost post = new HTTPPost(conn.getOutputStream(), boundary);
            //post.writeField("username", "zedcamcat");
            //post.writeField("password", "AirFreshener");
            //post.writeFile("media", "image/jpg", file);
            post.writeFile("image", "image/jpg", file);
            post.close();

            // Setup a regex for scanning the result for the ID of the picture.
            //
            Pattern pattern = Pattern.compile(".*?<mediaurl>http://twitpic.com/([^<]*+).*");
            String filename = "";

            // Create a reader to get the response of the POST.
            BufferedReader response = new BufferedReader(new InputStreamReader(conn.getInputStream()));

            // Loop over the response
            String line;
            while ((line=response.readLine()) != null) {
                filename = line;
            }
            response.close();

            // Return the url of the image.
            return filename;
        } catch (IOException e) {
            System.out.println(e.getMessage());
            return "client error";
        }
    }

}
